using System.Collections.Generic;
using System.Linq;
using ETestIT.Core;
using ETestIT.Core.DataInterfaces;
using NHibernate;
using NHibernate.Criterion;
using SharpArch.Data.NHibernate;

namespace ETestIT.Data
{
    public class CandidateRepository : Repository<Candidate>, ICandidateRepository
    {
        #region ICandidateRepository Members

        public IEnumerable<Candidate> SearchByExample(Candidate candidateExample)
        {
            ICriteria criteria = Session.CreateCriteria(typeof (Candidate));

            IfValIsNotNullEnlistAsLike("FirstName", candidateExample.FirstName, criteria);
            IfValIsNotNullEnlistAsLike("Surename", candidateExample.Surename, criteria);
            IfValIsNotNullEnlistAsLike("Email", candidateExample.Email, criteria);
            IfValIsNotNullEnlistAsLike("Phone", candidateExample.Phone, criteria);

            return criteria.List()
                .Cast<Candidate>()
                .Select(x => x);
        }

        #endregion

        private void IfValIsNotNullEnlistAsLike(string property, string propertyVal, ICriteria criteria)
        {
            if (string.IsNullOrEmpty(propertyVal) == false)
                criteria.Add(Restrictions.Like(property, "%" + propertyVal + "%"));
        }
    }
}